package com.easy.base.api.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.easy.base.api.model.dto.SessionUser;
import com.easy.base.api.model.entity.UserInfoEntity;
import com.easy.base.api.model.enums.SessionAttrName;
import com.easy.base.api.model.enums.ShowType;
import com.easy.base.api.model.exception.BizException;
import com.easy.base.api.repository.UserInfoRepository;
import com.easy.base.api.service.IUserInfoService;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

@Service
public class UserInfoService extends BaseService<UserInfoEntity, UserInfoRepository> implements IUserInfoService {

    @Resource
    private HttpSession session;

    @Override
    public Page<UserInfoEntity> selectEntities(UserInfoEntity model) {
        Page<UserInfoEntity> pages = jpa
                .findAllWithoutPassword(PageRequest.of(model.getCurrent() - 1, model.getPageSize()));
        return pages;
    }

    @Override
    public UserInfoEntity selectEntityByID(String id) {
        return jpa.findAllByIdWithoutPassword(id);
    }

    @Override
    public SessionUser login(String username, String password, String captcha) {
        Object captchaObj = session.getAttribute(SessionAttrName.LOGIN_CAPTCHA);
        if (captchaObj == null) {
            throw new BizException(HttpStatus.METHOD_NOT_ALLOWED, true, "验证码过期，请刷新",
                    ShowType.MessageWarn);
        }

        if (!captcha.toLowerCase().equals(captchaObj.toString().toLowerCase())) {
            throw new BizException(HttpStatus.UNAUTHORIZED, true, "验证码不正确", ShowType.MessageWarn);
        }

        SessionUser oldUser = (SessionUser) session.getAttribute(SessionAttrName.USER);
        if (oldUser != null) {
            return oldUser;
        }
        UserInfoEntity entity = jpa.findByUsernameAndPasswordAndValid(username, password, true);
        if (entity == null) {
            throw new BizException(HttpStatus.FORBIDDEN, true, "账号或密码不正确", ShowType.MessageWarn);
        }
        SessionUser user = new SessionUser(entity);
        session.setAttribute(SessionAttrName.USER, user);
        session.removeAttribute(SessionAttrName.LOGIN_CAPTCHA);
        return user;
    }

    @Override
    public void logout() {
        session.removeAttribute(SessionAttrName.USER);
    }

    @Override
    public SessionUser currentUser() {
        Object object = session.getAttribute(SessionAttrName.USER);
        if (object != null && object instanceof SessionUser) {
            SessionUser user = (SessionUser) object;
            return user;
        }
        throw new BizException(HttpStatus.UNAUTHORIZED, true, "会话已过期", ShowType.MessageWarn);
    }
}
